<template>
    <div class="container">
        <van-sticky>
            <div class="heads">
                <div class="search">
                    <div class="search_postion">
                        <div @click="selectPosition" style="height: 25px;display: flex;align-items: center">
                            <img src="../assets/index/position.svg" alt="" style="width: 15px;">
                        </div>
                        <div @click="selectPosition" style="height: 25px;display: flex;align-items: center">
                            <span class="position_text">{{ cityName }}</span>
                        </div>
                    </div>
                    <div class="search-wrapper">
                        <van-search :clearable="false" class="custom-search" v-model="value" placeholder="请输入福利名称"
                            shape="round" :show-action="true" @search="handleSearch" background="transparent">
                            <template #action>
                                <div @click.stop="handleSearch" class="search-button">搜索</div>
                            </template>
                        </van-search>
                    </div>
                </div>
            </div>
        </van-sticky>
        <van-tabs @click="onClick" v-model="active" animated title-active-color="#EE473B" swipe-threshold="5"
            color="#EE473B" title-inactive-color="#5B626A">
            <van-tab v-for="(item, index) in tabList" :title="item" :name="index" :key="index" />
        </van-tabs>
        <div class="welfareContent">
            <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
                <van-list v-model="loading" :finished="finished" finished-text="没有更多兑换商品了" class="movie-list">
                    <van-grid :column-num="3" gutter="5">
                        <van-grid-item v-for="(item, index) in welfareList" :key="index" icon="photo" text="标题"
                            @click="goDetail(item.product_no, item.imgs, item.officialPrice)">
                            <div class="box">
                                <div class="card-img-welfare">
                                    <img :src="item.imgs" class="poster-welfare">
                                </div>
                            </div>
                            <div class="card-title-welfare">{{ item.product_name }}</div>
                            <div class="exchange-btn">
                                <div class="price">¥{{ (item.officialPrice) }}</div>
                                <div class="text">兑换</div>
                            </div>
                        </van-grid-item>
                    </van-grid>
                </van-list>
            </van-pull-refresh>
        </div>
    </div>
</template>

<script>
import plantAPI from "@/api/plant";

export default {
    data() {
        return {
            isLoading: false,
            picsData: [],
            oldData: [],
            loading: false,
            finished: false,
            page: 1,
            list: [],
            cityName: '',
            value: '',
            active: 0,
            welfareList: [],
            tabList: []
        }
    },
    created() {

        this.cityName = localStorage.getItem("cityName") || '';
        this.initData()
    },
    methods: {
        async initData() {
            this.loading = true;
            try {
                const res = await plantAPI.conversionList();
                const productList = res.data || [];

                if (productList.length > 0) {
                    const firstProduct = productList[0];
                    const result = await plantAPI.directofficialPrice(firstProduct.product_no);
                    const productImages = result.data || {};

                    const imageMap = {};
                    Object.keys(productImages).forEach(key => {
                        imageMap[key] = productImages[key];
                    });
                    console.log(imageMap, 'productList')
                    this.oldData = productList.map(item => ({
                        ...item,
                        officialPrice: imageMap[item.product_no].officialPrice || '',
                        imgs: imageMap[item.product_no].productPath || ''
                    }));

                    this.tabList = [...new Set(
                        productList.map(item => item.type_name).filter(name => name)
                    )];
                    this.updateWelfareList();
                }
            } catch (error) {
            } finally {
                this.loading = false;
                this.finished = true;
            }
        },
        onRefresh() {
            this.welfareList = []
            this.initData()
            this.isLoading = false;
        },
        formatPrice(price) {
            const num = Number(price);
            if (isNaN(num)) return '0.00';
            return (num / 100).toFixed(2);
        },
        goDetail(productNo, imgs, price) {
            sessionStorage.setItem(
                'welfarePayData',
                JSON.stringify({
                    productNo,
                    imgs,
                    showPrice: price
                })
            );

            // 只带一个极短标识（没有也行）跳转到支付页
            window.location.replace(`https://xhjzh.life/welfarePay/?productNo=${productNo}`);
        },
        selectPosition() {
            this.$router.push({
                path: '/citySelect',
                query: { nowCity: this.cityName }
            });
        },
        onClick() {
            this.updateWelfareList();
        },
        handleSearch() {
            this.updateWelfareList();
        },
        updateWelfareList() {
            let filteredData = [...this.oldData];
            if (this.value) {
                const searchTerm = this.value.toLowerCase();
                filteredData = filteredData.filter(item =>
                    item.product_name.toLowerCase().includes(searchTerm)
                );
            }
            if (this.tabList.length > 0) {
                filteredData = filteredData.filter(
                    item => item.type_name === this.tabList[this.active]
                );
            }

            this.welfareList = filteredData;
        }
    }
};
</script>

<style lang="scss" scoped>
.search_postion {
    display: flex;
    align-items: center;
    margin-right: 10px;
    flex-shrink: 0;
    /* 防止位置信息被压缩 */
    max-width: 80px;
    /* 限制位置信息的最大宽度 */
}

.container {
    background: #F5F6F8;
    min-height: calc(100vh - 95px);
    padding-bottom: 95px;
}

::v-deep .van-grid-item__content {
    padding: 10px 0 !important;
}

::v-deep .van-sticky {
    background: #FFFFFF;
}

::v-deep .van-icon-search {
    color: #EE473B;
}

.search-wrapper {
    flex: 1;
    background: transparent;
}


.movie-card {
    background: #fff;
    width: 351px;
    margin: 8px auto 0;
    border-radius: 6px;

    .card-content {
        border-radius: 10px;
        background: #fff;
        margin: 0 10px;
        overflow: hidden;
        display: flex;
        align-items: center;
    }
}

.box {
    width: 78px;
    height: 78px;
    background: rgba(144, 144, 144, 0.08);
    border-radius: 4px;
    margin-bottom: 5px;
}

::v-deep .van-grid {
    margin-top: 10px;
}

::v-deep .van-grid-item__content {
    border-radius: 4px !important;
}

.card-img-welfare {
    position: relative;
    width: 55px;
    height: 55px;
    overflow: hidden;
    margin: 11px;
}

.poster-welfare {
    width: 55px;
    height: 55px;
    object-fit: cover;
}

.card-title-welfare {
    white-space: normal;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 1;
    -webkit-box-orient: vertical;
    width: 110px;
    margin: auto;
    text-align: center;
    height: 20px;
    font-family: PingFang SC;
    font-weight: 500;
    font-size: 13px;
    color: #333333;
}

.exchange-btn {
    height: 21px;
    position: relative;
    margin-top: 5px;
    gap: 8px;
    width: 78px;
}

.price {
    width: 50px;
    background: #EE473B;
    height: 21px;
    border-radius: 12px 0 0 12px;
    font-family: PingFang SC;
    font-size: 12px;
    color: #FFFFFF;
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;
}

.price::before {
    content: '';
    position: absolute;
    right: -3px;
    top: 0;
    width: 5px;
    height: 100%;
    background: #EE473B;
    transform: skewX(-9deg);
    transform-origin: top right;
    border-radius: 0;
}

.text {
    position: absolute;
    left: 48px;
    top: 0;
    width: 28px;
    height: 19px;
    line-height: 19px;
    border-radius: 0px 12px 12px 0px;
    font-family: PingFang SC;
    font-size: 10px;
    color: #EE473B;
    border: 1px solid #EE473B;
    display: inline-flex;
    align-items: center;
    justify-content: center;
}

.search {
    display: flex;
    align-items: center;
    padding: 8px 12px;
    width: 100%;
}

.search_postion {
    display: flex;
    align-items: center;
    margin-right: 10px;
    flex-shrink: 0;
    /* 防止位置信息被压缩 */
    max-width: 80px;
    /* 限制位置信息的最大宽度 */
}

.position_text {
    font-size: 14px;
    margin-left: 4px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.search-wrapper {
    flex: 1;
    min-width: 0;
    /* 防止flex item溢出 */
}

::v-deep .van-search {
    background: transparent !important;
    padding: 0;
    width: 100%;
    /* 确保搜索框占满可用空间 */

    &__content {
        background: #f7f8fa;
        width: 100%;
        /* 确保搜索内容区域占满可用空间 */
    }

    &__action {
        padding: 0 0 0 8px;
        background: transparent;
        flex-shrink: 0;
        /* 防止搜索按钮被压缩 */
    }
}

.search-button {
    color: #EE473B;
    padding: 0 8px;
    font-size: 14px;
    white-space: nowrap;
}
</style>